﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Loong.Net
{
    /// <summary>
    /// Internal object that represents the payload for uploading data.
    /// Not documented much -it's private anyway!
    /// </summary>
    public class MIMEPayload
    {
        private const String boundary = "------------328523758298hjcwuie";
        private byte[] data = new byte[0];

        public void AddValue(String name, String value)
        {
            String text;
            text = "--" + boundary + "\r\n";
            text += "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n";
            text += (value == null ? "" : value) + "\r\n";

            byte[] bytes = Encoding.ASCII.GetBytes(text);

            byte[] final = new byte[data.Length + bytes.Length];
            Buffer.BlockCopy(data, 0, final, 0, data.Length);
            Buffer.BlockCopy(bytes, 0, final, data.Length, bytes.Length);
            data = final;
        }

        public void AddFile(String name, String fileName)
        {
            String text;
            text = "--" + boundary + "\r\n";
            text += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n";
            text += "Content-Type: application/octet-stream\r\n\r\n";

            byte[] textBytes = Encoding.ASCII.GetBytes(text);
            byte[] fileBytes;

            try
            {
                using (FileStream fs = File.OpenRead(fileName))
                {
                    fileBytes = new byte[fs.Length];
                    fs.Read(fileBytes, 0, fileBytes.Length);
                }
            }
            catch (Exception)
            {
                fileBytes = new byte[0];
            }

            byte[] final = new byte[data.Length + textBytes.Length + fileBytes.Length + 2];
            Buffer.BlockCopy(data, 0, final, 0, data.Length);
            Buffer.BlockCopy(textBytes, 0, final, data.Length, textBytes.Length);
            Buffer.BlockCopy(fileBytes, 0, final, data.Length + textBytes.Length, fileBytes.Length);
            final[final.Length - 2] = 13;
            final[final.Length - 1] = 10;
            data = final;
        }

        public void Finish()
        {
            byte[] bytes = Encoding.ASCII.GetBytes("--" + boundary + "--");

            byte[] final = new byte[data.Length + bytes.Length];
            Buffer.BlockCopy(data, 0, final, 0, data.Length);
            Buffer.BlockCopy(bytes, 0, final, data.Length, bytes.Length);
            data = final;
        }

        public String Boundary
        {
            get
            {
                return boundary;
            }
        }

        public byte[] Data
        {
            get
            {
                return data;
            }
        }
    }
}
